package com.xingmang.common.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.xingmang.common.constant.ResponseData;
import com.xingmang.common.constant.ResultBean;
import com.xingmang.common.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @auther: hansom
 * @Version: 1.0
 * @create 2023/4/17 13:07
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //未登录异常
    @ExceptionHandler(value = NotLoginException.class)
    public ResultBean handleNotLoginException(NotLoginException e, HttpServletRequest request){
        log.error("鉴权错误:{}", e.getMessage());
        return ResponseData.error(ResultCode.AUTH_ERROR);
    }

    //请求参数异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultBean handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("请求参数错误:{}", e.getMessage());
        return ResponseData.error(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * 权限码异常
     */
    @ExceptionHandler(value={NotPermissionException.class, NotRoleException.class})
    public ResultBean handleNotPermissionException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址:{},权限码校验失败:{}", requestURI, e.getMessage());
        return ResponseData.error(ResultCode.FORBIDDEN);
    }

    /**
     * 其他异常
     * @param e
     * @return
     */
    @ExceptionHandler(value=Exception.class)
    public ResultBean handleException(Exception e){
        log.error("全局其他异常:{}", e);
        return ResponseData.error(ResultCode.ERROR);
    }
}
